#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2022-8-7 0:02
# @file     : crontab.py
# @Software : PyCharm
# ======================================#


import os
import sys

from base.cls import ParseConf, Ding,QYWX,FeiShu
from base.func import get_dir_file
from monitor.core import Monitor
from monitor.settings import MAX_WORKER, FILE_CONFIG_FILTER
from settings import BASE_DIR

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import ipaddress
from concurrent.futures import ProcessPoolExecutor


class App:
    def __init__(self):
        pass

    def start(self):
        """
        1. 获取file
        2. 获取file_info
        3. check and send dingding
        :return:
        """
        dir_path, files = self.get_dir_and_files()
        files_info = self.get_files_info(dir_path, files)
        self.check_files_info(files_info)

    def get_dir_and_files(self):
        dir_path = os.path.join(BASE_DIR, "monitor/conf")
        files = get_dir_file(dir_path, filter='port', file_bool=True, dir_bool=False)
        return dir_path, files

    def get_files_info(self, dir_path, files):
        files_info = {}
        for file in files:
            path = os.path.join(dir_path, file)
            parse = ParseConf(path)
            files_info[file] = parse.get_sections_info()

        return files_info

    def check_files_info(self, files_info):
        if not files_info:
            return None

        for file, infos in files_info.items():
            for section, options in infos.items():
                if "default" == section:
                    continue

                try:
                    ip = section.split('-')[-1]
                    # 解析的非ip地址
                    if not ipaddress.ip_address(ip):
                        continue
                    if "dingtoken" in infos[section].keys():
                        token = infos[section]["dingtoken"]
                        ding = Ding(token)
                    elif "qywxtoken" in infos[section].keys():
                        token = infos[section]["qywxtoken"]
                        ding = QYWX(token)
                    elif "feishutoken" in infos[section].keys():
                        token = infos[section]["feishutoken"]
                        ding = FeiShu(token)
                    else:
                        raise Exception("not config token!")
                    with ProcessPoolExecutor(max_workers=MAX_WORKER) as executor:
                        executor.submit(self.check_and_send_msg, section, ip, options, ding)
                except:
                    continue

    def check_and_send_msg(self, section, ip, options, ding):
        monitor = Monitor()
        for app, port in options.items():
            if app in FILE_CONFIG_FILTER:
                continue
            try:
                port = int(port)
                if port > 65335 or port < 1:
                    ding.send_text(f"{section}-{app}: port={port} is valiad!")
                    continue

                status_info = monitor.port(ip, port)
                if not status_info["status"]:
                    strs = f"{section}-{app}-{port} check failed, please check it"
                    ding.send_text(strs)
                else:
                    # strs=f"{section}-{app}-{port} is ok!"
                    # ding.send_text(strs)
                    pass
            except Exception as e:
                ding.send_text(f"{section}-{app} is valiad!")


if __name__ == "__main__":
    app = App()
    app.start()
